import { queryAdminlist, queryAdmininfo, queryCurrent, updateAdmininfo, addAdmin, removeAdmin,fetchResetAdminPwd} from '@/services/admin';
import { message } from 'antd';
import router from 'umi/router';
export default {
  namespace: 'admin',

  state: {
    data: {
      list: [],
      pagination: {},
    },
    userInfo: {},
    adminInfo: {},
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryAdminlist, payload);
      yield put({
        type: 'save',
        payload: {
          list: response.data,
          pagination: {
            total: response.meta.total,
            pageSize: 10,
            current: parseInt(response.meta.current_page, 10) || 1,
          },
        },
      });
    },
    *fetchUserInfo({ payload }, { call, put }) {// 获取当前登录的管理员详情
      const response = yield call(queryCurrent, payload);
      console.log(response);
      yield put({
        type: 'saveUserinfo',
        payload: response.data,
      });
    },
    *fetchAdmininfo({ payload }, { call, put }) { // 获取管理员详情
      const response = yield call(queryAdmininfo, payload);
      yield put({
        type: 'saveAdmininfo',
        payload: response.data,
      });
    },
    *updateRadio({ payload }, { call, put }) {
      yield put({
        type: 'saveAdmininfo',
        payload: payload,
      });
    },
    *addAdmin({ payload }, { call, put }) {
      const response = yield call(addAdmin, payload);
      if (response.status === 'success') {
        message.success('添加成功');
        router.push('/adminlist/table-list');
      } else {
        message.error('添加失败');
      }

    },
    *update({ payload, callback }, { call, put }) {
      const response = yield call(updateAdmininfo, payload);
      console.log(response.status);
      if (response.status === 'success') {
        message.success('更新成功');
        router.push('/adminlist/table-list');
      } else {
        message.error('更新失败');
      }

    },
    *remove({ payload, callback }, { call, put }) {
      const response = yield call(removeAdmin, payload);
      if (response.status === 'success') {
        message.success('更新成功');
        yield put({ type: 'fetch' });
      }else {
        message.error('更新失败');
      }

    },
    *resetAdminPwd({ payload, callback }, { call, put }){
      const response = yield call(fetchResetAdminPwd, payload);
      if (response.status === 'success') {
        message.success('重置成功');
      }else {
        message.error('重置失败');
      }
    }
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    saveUserinfo(state, action) {
      return {
        ...state,
        userInfo: action.payload,
      };
    },
    saveAdmininfo(state, action) {
      return {
        ...state,
        adminInfo: action.payload,
      };
    },

  },
};
